from django.shortcuts import render
from django.views import View
from django import http
from django.core.cache import cache
import logging

from areas.models import Area

# Create your views here.

# 创建日志生成器
logger = logging.getLogger('django')


class SubAreasView(View):
    def get(self, request, pk):
        sub_data = cache.get('sub_area_' + pk)
        if not sub_data:
            try:
                parent_model = Area.objects.get(pk=pk)
                sub_models = Area.objects.filter(parent=pk)
            except Exception as e:
                logger.error(e)
                return http.JsonResponse({'code': 400, 'errmsg': '访问数据库失败'})

            sub_data = {
                'id': parent_model.id,
                'name': parent_model.name,
                'subs': []
            }
            for area in sub_models:
                sub_data['subs'].append({
                    'id': area.id,
                    'name': area.name
                })
            # 缓存市或区数据
            cache.set('sub_area_' + pk, sub_data, 3600)

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'sub_data': sub_data})


class ProvinceAreasView(View):
    def get(self, request):

        # 增加逻辑,判断是否有缓存
        province_list = cache.get('province_list')
        if not province_list:
            province_area = Area.objects.filter(parent__isnull=True)
            province_list = []
            for province in province_area:
                province_list.append({
                    'id': province.id,
                    'name': province.name
                })
            cache.set('province_list', province_list, 3600)

        return http.JsonResponse({'code': 0, 'errmsg': 'ok', 'province_list': province_list})



